<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2021/3/20
 * Time: 16:16
 */

namespace App\Services;

use App\Expert;
use App\Patent;
use GuzzleHttp\Client;

class ApiSyncService
{
    protected $apiSync = false;
    protected $base_uri = '';
    protected $api_key;
    protected $api_secret;
    protected $queryData = [];

    public function __construct()
    {
        $this->apiSync = config('sesame.api_sync');
        $this->base_uri = config('sesame.api_uri');
        if ($this->base_uri) {
            $this->base_uri = rtrim($this->base_uri, '/') . '/';
        }
        $this->api_key = config('sesame.api_key');
        $this->api_secret = config('sesame.api_secret');
    }

    public function syncGoods(Patent $goods)
    {
        $uri = 'syncGoods';
        $this->sendRequest($uri, [
            'patent_sn' => $goods->patent_sn,
            'patent_name' => $goods->patent_name,
            'apply_date' => $goods->apply_date ?: null,
            'patent_person' => $goods->patent_person,
            'inventor' => $goods->inventor ?? '',
            'legal_status' => $goods->legal_status ?? '',
            'ipc_main' => $goods->ipc_main ?? '',
            'patent_type_id' => $goods->patent_type_id ?? '',
            'patent_domain_id' => $goods->cate_id,
            'third_goods_id' => $goods->id,
            'patent_cert' => $goods->patent_cert ?? '',
            'sale_mode' => collect($goods->sale_mode)->implode(','),
            'sale_state' => $goods->sale_status ?? 0,
            'amount' => $goods->sale_amount,
        ]);
    }

    public function syncGoodsStateBatch(array $ids, $state)
    {
        $this->sendRequest('syncGoodsState', [
            'state' => $state,
            'ids' => $ids
        ]);
    }

    public function syncExpert(Expert $expert)
    {
        $this->sendRequest('syncExpert', $expert->toArray());
    }

    public function syncExpertStateBatch(array $ids, $state)
    {
        $this->sendRequest('syncExpertState', [
            'state' => $state,
            'ids' => $ids
        ]);
    }

    protected function sendRequest($uri, $data)
    {
        if (!$this->apiSync || !$this->api_key || !$this->api_secret || !$this->base_uri) {
            return false;
        }
        $secret_key = config('app.sesame_key');
        $secret = config('app.sesame_secret');
        if (!$secret_key || !$secret) {
            return false;
        }

        $client = new Client(['base_uri' => $this->base_uri]);
        $timestamp = time();
        return $client->request('POST', $uri, [
            'form_params' => $data,
            'query' => [
                'sign' => $this->getSign($secret, $timestamp),
                'timestamp' => $timestamp,
                'secret_key' => $secret_key,
            ]
        ]);
    }

    protected function getSign($secret, $timestamp)
    {
        return md5($timestamp . $secret);
    }

}
